<template>
    <view class="edit-address-container">
        <u-navbar :title="form.id ? '编辑地址' : '新增地址'" @leftClick="navigateBack" :safeAreaInsetTop="true" :placeholder="true"></u-navbar>
        <view class="form-content">
            <view class="form-item">
                <text class="form-label">收货人</text>
                <input type="text" v-model="form.name" placeholder="请输入收货人姓名" class="form-input" />
            </view>
            <view class="form-item">
                <text class="form-label">手机号码</text>
                <input type="number" v-model="form.phone" placeholder="请输入手机号码" class="form-input" />
            </view>
            <view class="form-item" @click="showRegionPicker = true">
                <text class="form-label">所在地区</text>
                <view class="region-picker">
                    <text v-if="form.province">{{form.province}} {{form.city}} {{form.district}}</text>
                    <text v-else class="placeholder">请选择省/市/县</text>
                    <text class="arrow-right">></text>
                </view>
            </view>
            <view class="form-item">
                <text class="form-label">详细地址</text>
                <textarea v-model="form.detail" placeholder="请输入详细地址" class="form-textarea" auto-height />
            </view>
            <view class="form-item">
                <text class="form-label">设为默认地址</text>
                <switch :checked="form.isDefault" @change="onDefaultChange" color="#FF6600" />
            </view>
        </view>
        <view class="save-btn-container">
            <button class="save-btn" @click="saveAddress">保 存</button>
        </view>
        
        <!-- 调试信息 -->
        <!-- <view class="debug-section" v-if="true">
            <view class="debug-info">
                <text>表单ID: {{form.id}}</text>
                <text>ID类型: {{typeof form.id}}</text>
            </view>
            <button class="debug-btn" @click="debugForm">调试表单</button>
        </view> -->
        
		<u-picker 
            :show="showRegionPicker" 
            :columns="regionColumns" 
            @confirm="onRegionConfirm" 
            @cancel="showRegionPicker = false" 
            @change="onPickerChange"
            :defaultIndex="pickerValue"
        ></u-picker>
    </view>
</template>

<script>
import { addressApi } from '../../src/api/address.js';

export default {
    data() {
        return {
            form: {
                id: null,
                name: '',
                phone: '',
                province: '',
                city: '',
                district: '',
                detail: '',
                isDefault: false,
            },
            showRegionPicker: false,
            regionData: [],
            regionColumns: [],
            pickerValue: [0, 0, 0],
        };
    },
    onLoad(options) {
        console.log('地址编辑页面加载，参数:', options);
        if (options.id) {
            this.form.id = options.id;
            console.log('加载地址ID:', this.form.id);
            this.loadAddress();
        }
        this.loadRegions();
    },
    methods: {
        loadAddress() {
            if (!this.form.id) return;
            console.log('开始加载地址详情，ID:', this.form.id);
            addressApi.get(this.form.id).then(res => {
                console.log('地址详情返回:', JSON.stringify(res));
                if (res.code === 200 && res.data) {
                    // 保留ID，只更新其他字段
                    const addressData = res.data;
                    console.log('原始地址数据:', JSON.stringify(addressData));
                    
                    // 确保字段名称匹配
                    this.form = {
                        id: this.form.id,
                        name: addressData.consignee || addressData.name,
                        phone: addressData.phone,
                        province: addressData.province,
                        city: addressData.city,
                        district: addressData.district,
                        detail: addressData.detailAddress || addressData.detail,
                        isDefault: !!addressData.isDefault
                    };
                    
                    console.log('处理后的表单数据:', JSON.stringify(this.form));
                }
            }).catch(err => {
                console.error('加载地址详情失败:', err);
            });
        },
        async loadRegions() {
            const res = await addressApi.getRegions();
            if (res.code === 200 && res.data) {
                this.regionData = res.data;
                this.updatePickerColumns();
            }
        },
        updatePickerColumns(pIndex = 0, cIndex = 0) {
            if (!this.regionData.length) return;
            const provinces = this.regionData.map(p => p.name);
            const cities = this.regionData[pIndex]?.children.map(c => c.name) || [];
            const districts = this.regionData[pIndex]?.children[cIndex]?.children.map(d => d.name) || [];
            this.regionColumns = [provinces, cities, districts];
        },
        onPickerChange(e) {
            const [pIndex, cIndex, dIndex] = e.detail.value;
            if (this.pickerValue[0] !== pIndex) {
                this.updatePickerColumns(pIndex, 0);
                this.pickerValue = [pIndex, 0, 0];
            } else if (this.pickerValue[1] !== cIndex) {
                this.updatePickerColumns(pIndex, cIndex);
                this.pickerValue = [pIndex, cIndex, 0];
            } else {
                this.pickerValue = e.detail.value;
            }
        },
        onRegionConfirm() {
            const [pIndex, cIndex, dIndex] = this.pickerValue;
            this.form.province = this.regionColumns[0][pIndex];
            this.form.city = this.regionColumns[1][cIndex];
            this.form.district = this.regionColumns[2][dIndex];
            this.showRegionPicker = false;
        },
        onDefaultChange(e) {
            this.form.isDefault = e.detail.value;
        },
        saveAddress() {
            console.log('保存地址，表单数据:', JSON.stringify(this.form));
            
            // 转换字段名称，适配后端API
            const dataToSave = {
                id: this.form.id,
                consignee: this.form.name,
                phone: this.form.phone,
                province: this.form.province,
                city: this.form.city,
                district: this.form.district,
                detailAddress: this.form.detail,
                isDefault: this.form.isDefault
            };
            
            console.log('转换后的保存数据:', JSON.stringify(dataToSave));
            
            // 根据是否存在ID来决定调用哪个API
            const apiCall = dataToSave.id 
                ? addressApi.update(dataToSave) 
                : addressApi.add(dataToSave);
                
            apiCall.then(res => {
                console.log('保存地址返回:', JSON.stringify(res));
                if (res.code === 200) {
                    // 保存返回的地址对象到本地存储，包含ID
                    if (res.data) {
                        console.log('保存成功，返回的地址对象:', JSON.stringify(res.data));
                        
                        // 转换后端字段名称为前端字段名称
                        const savedAddress = {
                            id: res.data.id,
                            name: res.data.consignee || res.data.name,
                            phone: res.data.phone,
                            province: res.data.province,
                            city: res.data.city,
                            district: res.data.district,
                            detail: res.data.detailAddress || res.data.detail,
                            isDefault: !!res.data.isDefault,
                            userId: res.data.userId
                        };
                        
                        console.log('转换后的地址对象:', JSON.stringify(savedAddress));
                        
                        // 如果是从确认订单页面进入，则设置选中的地址
                        const pages = getCurrentPages();
                        const prevPage = pages[pages.length - 2];
                        if (prevPage && prevPage.route && prevPage.route.includes('order/confirm')) {
                            console.log('从确认订单页面进入，设置选中地址');
                            uni.setStorageSync('selectedAddress', savedAddress);
                        }
                    }
                    
                    uni.showToast({ title: '保存成功' });
                    uni.navigateBack();
                } else {
                    uni.showToast({ title: res.msg || '保存失败', icon: 'none' });
                }
            }).catch(err => {
                console.error('保存地址失败:', err);
                uni.showToast({ title: '请求失败', icon: 'none' });
            });
        },
        navigateBack() {
            uni.navigateBack();
        },
        debugForm() {
            console.log('当前表单数据:', JSON.stringify(this.form));
            console.log('表单ID:', this.form.id);
            console.log('表单ID类型:', typeof this.form.id);
            
            uni.showModal({
                title: '表单信息',
                content: `ID: ${this.form.id}\n类型: ${typeof this.form.id}\n详情: ${JSON.stringify(this.form)}`,
                showCancel: false
            });
        },
    },
};
</script>

<style scoped>
.edit-address-container {
    background-color: #f5f5f5;
    min-height: 100vh;
}
.form-content {
    margin: 20rpx;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 30rpx;
}
.form-item {
    display: flex;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    font-size: 28rpx;
}
.form-item:last-child {
    border-bottom: none;
}
.form-label {
    width: 180rpx;
    color: #333;
}
.form-input, .form-textarea {
    flex: 1;
    color: #333;
}
.form-textarea {
    padding-top: 4rpx;
    min-height: 100rpx;
}
.region-picker {
    flex: 1;
    display: flex;
    justify-content: space-between;
}
.placeholder {
    color: #999;
}
.arrow-right {
    color: #999;
    margin-left: 10rpx;
}
.save-btn-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    background-color: #f5f5f5;
}
.save-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #FF6600;
    color: #fff;
    border-radius: 40rpx;
    font-size: 32rpx;
    border: none;
}
/* 调试样式 */
.debug-section {
    margin: 20rpx;
    padding: 20rpx;
    background-color: #f0f8ff;
    border-radius: 10rpx;
}

.debug-info {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
    display: flex;
    flex-direction: column;
}

.debug-btn {
    background-color: #007AFF;
    color: #fff;
    font-size: 24rpx;
    padding: 10rpx 20rpx;
    border-radius: 10rpx;
    margin-top: 10rpx;
}
</style> 